<?php

namespace app\admin\controller\yxerp;

use app\common\controller\Backend;
use ba\Tree;

/**
 * 部门管理
 */
class Department extends Backend
{
    /**
     * Department模型对象
     * @var object
     * @phpstan-var \app\admin\model\yxerp\Department
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['id', 'name', 'code'];

    /**
     * @var Tree
     */
    protected Tree $tree;

    /**
     * 是否组装Tree
     * @var bool
     */
    protected bool $assembleTree;

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\yxerp\Department();
        $this->tree  = Tree::instance();

        $isTree = $this->request->param('isTree', true);
        // 是否组装树状
        $this->assembleTree = $isTree;
    }

    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        $this->success('', [
            'list'   => $this->getDepartments(),
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 重写select方法
     */
    public function select(): void
    {
        $data = $this->getDepartments([['status', '=', '1']]);

        if ($this->assembleTree) {
            $data = $this->tree->assembleTree($this->tree->getTreeArray($data, 'name'));
        }
        $this->success('', [
            'options' => $data
        ]);
    }

    /**
     * 部门树形选择器专用接口
     */
    public function treeSelect(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        $this->success('', [
            'list'   => $this->getDepartments(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 获取部门列表
     */
    protected function getDepartments($where = []): array
    {
        $pk = $this->model->getPk();

        // 字段排序
        $order = $this->request->get("order/s", "");
        $sort  = $this->request->get("sort/s", $pk);
        
        if ($sort && $order) {
            $order = [$sort => $order];
        } else {
            $order = ['sort' => 'asc', $pk => 'asc'];
        }

        $keyword = $this->request->request('quickSearch', '');
        if ($keyword) {
            $keywordWhere = [];
            foreach ($this->quickSearchField as $field) {
                $keywordWhere[] = [$field, 'LIKE', '%' . $keyword . '%'];
            }
            $where[] = array_merge(['or'], $keywordWhere);
        }

        // 查询数据
        $list = $this->model->where($where)->order($order)->select();
        // 转换为数组并触发获取器
        $list = $list->toArray();

        return $this->assembleTree ? $this->tree->assembleChild($list) : $list;
    }

    /**
     * 编辑
     */
    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            $this->model->startTrans();
            try {
                // 验证父部门是否形成循环
                if (isset($data['pid']) && $data['pid'] > 0) {
                    // 确保父部门不是自己的子部门
                    $parent = $this->model->where('id', $data['pid'])->find();
                    if ($parent['pid'] == $row['id']) {
                        $parent->pid = 0;
                        $parent->save();
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (\Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 删除
     */
    public function del(): void
    {
        $ids = $this->request->param('ids/a', []);

        // 检查是否有子部门
        $childrenExists = $this->model->where('pid', 'in', $ids)->find();
        if ($childrenExists) {
            $this->error(__('Please delete child departments first, or use batch deletion'));
        }
        
        parent::del();
    }

    /**
     * 若需重写其他方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}